//
//  ZCRaisePayVC.m
//  zctx
//
//  Created by 郭亚京 on 15/10/12.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCRaisePayVC.h"
#import "ZCRaisePayCell.h"
#import "WXApi.h"
#import "ZCPayshareViewController.h"
@interface ZCRaisePayVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong)NSString *payType;
@end

@implementation ZCRaisePayVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.payType = @"0";
    [self.navigationItem setTitle:@"确认支付"];
    NSLog(@"self.index = %ld",(long)self.index);
    
    self.automaticallyAdjustsScrollViewInsets =NO;
    [self initnavegation]; //导航栏
    [self initTableViewHead]; //tableView head
    [self initFootView];
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCRaisePayCell" bundle:nil] forCellReuseIdentifier:@"playcell"];
    
    NSInteger price = [[NSString stringWithFormat:@"%@",self.priceStr]integerValue];
    if (price>0) {
        self.moneyTextFiled.userInteractionEnabled = NO;
        self.moneyTextFiled.text = [NSString stringWithFormat:@"%ld",(long)price];
    }
    if ([self.markStr isEqualToString:@"1"]) {
        self.moneyTextFiled.placeholder = @"至少10元";
    }
    
    
    [self weichatResult];//微信支付结果通知
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    ProgressDismiss;
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initTableViewHead{

    UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    headView.backgroundColor = [UIColor whiteColor];
    UIView *bgheadView = [UIView new];
    [headView addSubview:bgheadView];
    bgheadView.backgroundColor = [UIColor colorWithHexString:@"#ebeded"];
    [bgheadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.top).with.offset(0);
        make.left.equalTo(headView).with.offset(0);
        make.right.equalTo(headView).with.offset(0);
        make.height.mas_equalTo(@10);
    }];
    
    UIView *newView = [UIView new];
    [headView addSubview:newView];
    [newView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.top).with.offset(10);
        make.left.equalTo(headView).with.offset(0);
        make.right.equalTo(headView).with.offset(0);
        make.bottom.equalTo(headView).with.offset(0);
    }];
    
    UILabel *leftlable = [UILabel new];
    [newView addSubview:leftlable];
    leftlable.font = [UIFont systemFontOfSize:17];
    leftlable.textColor = [UIColor colorWithHexString:@"#333333"];
    [leftlable setText:@"支付方式"];
    //        [leftlable setText:@"最新检测结果"];
    [leftlable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(newView.mas_centerY);
        make.left.equalTo(newView).with.offset(20);
        make.height.mas_equalTo(@30);
        make.width.mas_equalTo(@150);
    }];
    self.tableView.tableHeaderView = headView;
}

-(void)initFootView{
    
    UIView * footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    UIButton *okButton = [UIButton new];
    [footView addSubview:okButton];
    okButton.layer.cornerRadius = 5.0f;
    [okButton setTitle:@"确认" forState:UIControlStateNormal];
    okButton.backgroundColor = [UIColor colorWithHexString:@"#03Ab9e"];
    [okButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footView.top).with.offset(40);
        make.left.equalTo(footView).with.offset(50);
        make.right.equalTo(footView).with.offset(-50);
        make.height.mas_equalTo(@40);
    }];
    okButton.userInteractionEnabled = YES;
    [okButton addTarget:self action:@selector(senderOKButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = footView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid = @"playcell";
    ZCRaisePayCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexpath = indexPath;
    NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:firstPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 81;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.moneyTextFiled resignFirstResponder];
    self.payType = [NSString stringWithFormat:@"%lu", (long)indexPath.row];

    NSLog(@"indexpath.row = %ld",(long)indexPath.row);
}


#pragma mark 确认支付
-(void)senderOKButtonClick{
    NSLog(@"点击了支付--");
    if ([self.markStr isEqualToString:@"1"]) {
        if ([self.moneyTextFiled.text integerValue]<10) {
            [SVProgressHUD showErrorWithStatus:@"支付金额至少10元"];
            return;
        }
    }
    
    if ([self.moneyTextFiled.text intValue] <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请重新输入支付金额"];
        return;
    }
//    if ([self.payType isEqualToString:@"0"]) {
//        NSLog(@"支付宝支付");
//        [self aliPayButtonClick];
//    } else
    
    if ([self.payType isEqualToString:@"0"]) {
        [self wxButtonClick];
    } else if ([self.payType isEqualToString:@"1"]) {
        
    }

}

#pragma mark 微信支付
- (void)wxButtonClick{
    
    NSInteger money = [self.moneyTextFiled.text integerValue]*100;
    NSString *moneyStr = [NSString stringWithFormat:@"%ld",(long)money];
    
    NSLog(@"%@,%@,%@,%@,%@",UserModel.mid,UserModel.password,@"1",self.pid,moneyStr);
    [SVProgressHUD showWithStatus:@"支付中..."];
    [NetworkManager requestFoundingPayitWithMid:UserModel.mid password:UserModel.password type:@"1" fdid:self.pid donate:moneyStr success:^(NSDictionary *dictResponse) {
        ProgressDismiss;
        
        NSDictionary *dict =(NSDictionary *)[dictResponse objectForKey:@"content"];
        PayReq *req = [[PayReq alloc] init];
        req.prepayId = [NSString stringWithFormat:@"%@",[dict objectForKey:@"prepayId"]];
        req.partnerId = [NSString stringWithFormat:@"%@",[dict objectForKey:@"partnerId"]];
        req.package = [NSString stringWithFormat:@"%@",[dict objectForKey:@"package"]];
        req.timeStamp = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"timeStamp"]]intValue];
        req.sign = [NSString stringWithFormat:@"%@",[dict objectForKey:@"sign"]];
        req.nonceStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"nonceStr"]];
        [WXApi sendReq:req];
    } failure:^(NSError *error) {
    }];

}

#pragma mark 支付宝支付
- (void)aliPayButtonClick {
    
//    [self paysharesuccessUI];
    
//    [alipayManager payOrderWithTitle:self.model.name price:self.model.final_price callback:^(NSDictionary *resultDic) {
//        [SVProgressHUD dismiss];
//        
//        NSString *result = @"";
//        if ([[resultDic objectForKey:@"resultStatus"] intValue] == 9000 && [[resultDic objectForKey:@"success"] isEqualToString:@"true"]) {
//            result = @"支付成功";
//        } else {
//            result = @"支付失败";
//        }
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:result message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        alertView.tag = 2;
//        [alertView show];
//    }];
}

-(void)weichatResult{
    [[NSNotificationCenter defaultCenter] addObserverForName:@"WXPayResult" object:nil queue:NSOperationQueuePriorityNormal usingBlock:^(NSNotification *note) {
        NSLog(@"%@", [note.userInfo objectForKey:@"payCode"]);
        
        NSString *code = [note.userInfo objectForKey:@"payCode"];
        
        [SVProgressHUD dismiss];
        
        NSString *result = @"";
        if ([code isEqualToString:@"0"]) {
            [SVProgressHUD showSuccessWithStatus:@"支付成功"];
//            result = @"支付成功";
            [self paysharesuccessUI];
        } else if ([code isEqualToString:@"-2"]) {
            result = @"支付取消";
            [self alertViewShow:result];
        } else {
            result = @"支付失败";
            [self alertViewShow:result];
        }
        
    }];
}

-(void)alertViewShow:(NSString *)result{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:result message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alertView.tag = 1;
    [alertView show];
}
#pragma mark 支付成功界面
-(void)paysharesuccessUI{
    ZCPayshareViewController *zcvc = [[ZCPayshareViewController alloc]init];
    zcvc.pid = self.pid;
    zcvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:zcvc animated:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.moneyTextFiled resignFirstResponder];
    return YES;
}

-(void)resignfirst{
    [self.moneyTextFiled resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
